import { uploadFile } from "@/api/file";
import { addUser, changeUserInfo } from "@/api/system/user";
import { User } from "@/types/system/user";
import { deleteFileInf } from "@/utils/deleteFileInf";
import { PlusOutlined } from "@ant-design/icons";
import {
  Form,
  Input,
  message,
  Modal,
  Select,
  Spin,
  Switch,
  Upload,
  UploadFile,
} from "antd";
import { useForm } from "antd/es/form/Form";
import { useEffect, useState } from "react";
interface Props {
  isModalOpen: boolean;
  optionType: "add" | "edit";
  oldInfo?: User.Row;
  close?: () => void;
  change?: () => void;
}
export default function OptionForm(props: Props) {
  const [loading, setLoading] = useState(false);
  const [form] = useForm();
  const [type, setType] = useState("0");
  const [status, setStatus] = useState("0");
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [messageApi] = message.useMessage();
  const uploadFileInf = async (file: File | string | Blob) => {
    if (typeof file === "string") return;
    const formData = new FormData();
    formData.append("file", file);
    try {
      const res = await uploadFile(formData);
      const url = fileList[0] && fileList[0].url ? fileList[0].url : "";
      if (url) {
        deleteFileInf(url);
      }

      if (res.data) {
        setFileList([
          {
            uid: "-1",
            name: "",
            status: "done",
            url: res.data,
          },
        ]);
      }
    } catch (error) {
      console.error(error);
    }
  };
  /**
   * 添加接口
   * @param data
   */
  const addInf = async (data: User.Form) => {
    setLoading(true);
    const res = await addUser(data);
    setLoading(false);
    if (res.code === 200) {
      messageApi.success("新增成功");
      props.close && props.close();
      props.change && props.change();
    }
  };
  /**
   * 修改接口
   * @param data
   */
  const updateInf = async (data: User.Form) => {
    setLoading(true);
    const res = await changeUserInfo(data);
    setLoading(false);
    if (res.code === 200) {
      messageApi.success("修改成功");
      props.close && props.close();
      props.change && props.change();
    }
  };
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const { userName, password, nickName, email, phonenumber, sex } = values;
      const avatar = fileList[0] && fileList[0].url ? fileList[0].url : "";
      const params: User.Form = {
        userName,
        nickName,
        email,
        phonenumber,
        sex,
        avatar,
        status,
        type: props.optionType === "add" ? "0" : props.oldInfo?.type || "0",
      };
      if (props.optionType === "add") {
        params.password = password;
        addInf(params);
      } else if (props.optionType === "edit") {
        updateInf({
          ...(props.oldInfo || {}),
          ...params,
          id: props.oldInfo?.id,
        });
      }
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };
  useEffect(() => {
    if (props.optionType === "edit") {
      form.setFieldsValue(props.oldInfo || {});
      setStatus(props.oldInfo?.status || "0");
      setType(props.oldInfo?.type || "0");
      props.oldInfo?.avatar &&
      setFileList([
        {
          uid: "-1",
          name: "",
          status: "done",
          url: props.oldInfo.avatar,
        },
      ]);
    }
  }, [form, props.oldInfo, props.optionType]);
  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );
  return (
    <Modal
      title={props.optionType === "add" ? "新增用户" : "修改用户"}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={() => props.close && props.close()}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          initialValues={{
            sex: "0",
          }}
          name="roleOptionForm"
          size="middle"
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item<User.Form> name="avatar" label="头像">
            <Upload
              name="avatar"
              listType="picture-circle"
              className="avatar-uploader"
              action="#"
              fileList={fileList}
              customRequest={(file) => uploadFileInf(file.file)}
              onRemove={async () => {
                const url =
                  fileList[0] && fileList[0].url ? fileList[0].url : "";
                if (url) {
                  deleteFileInf(url);
                }
                setFileList([]);
              }}
            >
              {fileList.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>

          <Form.Item<User.Form>
            name="userName"
            label="用户名"
            rules={[{ required: true, message: "请输入" }]}
          >
            <Input />
          </Form.Item>
          {props.optionType === "add" && (
            <Form.Item<User.Form>
              name="password"
              label="密码"
              rules={[{ required: true, message: "请输入" }]}
            >
              <Input.Password />
            </Form.Item>
          )}
          <Form.Item<User.Form>
            name="nickName"
            label="用户昵称"
            rules={[{ required: true, message: "请输入" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item<User.Form>
            name="email"
            label="邮箱"
            rules={[{ required: true, message: "请输入" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item<User.Form>
            name="phonenumber"
            label="手机号"
            rules={[{ required: true, message: "请输入" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item<User.Form> name="sex" label="性别">
            <Select
              style={{ width: 120 }}
              options={[
                { value: "0", label: "男" },
                { value: "1", label: "女" },
                { value: "2", label: "保密" },
              ]}
            />
          </Form.Item>
          {type === "0" && (
            <Form.Item<User.Form> name="status" label="账号状态">
              <Switch
                checkedChildren="正常"
                unCheckedChildren="停用"
                checked={status === "0"}
                onChange={ () => { 
                  setStatus(status === "0" ? "1" : "0");
                }}
              />
            </Form.Item>
          )}
        </Form>
      </Spin>
    </Modal>
  );
}
